//
//  XKStatusViewModel.swift
//  XKWeibo
//
//  Created by 小k on 15/11/13.
//  Copyright © 2015年 小k. All rights reserved.
//

import UIKit

class XKStatusViewModel: CustomStringConvertible {
    
    /// 微博数据模型
    var status: XKStatus
    
    /// 表格的可重用表示符号
    var cellId: String {
        return status.retweeted_status != nil ? StatusCellRetweetedId : StatusCellNormalID
    }
    
    /// 缓存行高
    lazy var rowHeight: CGFloat = {
        var cell: XKStatusCell
        // 实例化 cell
        if self.status.retweeted_status != nil {
            cell = XKStatusRetweetedCell(style: .Default, reuseIdentifier: StatusCellRetweetedId)
        } else {
            cell = XKStatusNormalCell(style: .Default, reuseIdentifier: StatusCellNormalID)
        }
        return cell.rowHeight(self)
    }()
    
    /// 用户头像地址
    var userProfileUrl: NSURL {
        return NSURL(string: status.user?.profile_image_url ?? "")!
    }
    /// 用户默认头像
    var userDefaultImage: UIImage {
        return UIImage(named: "avatar_default_big")!
    }
    
    /// 用户会员图标
    var userMemberImage: UIImage? {
        
        // 根据 mbrank 来生成图像
        if status.user?.mbrank > 0 && status.user?.mbrank < 7 {
            return UIImage(named: "common_icon_membership_level\(status.user!.mbrank)")
        }
        return nil
    }
    
    /// 用户认证图像 认证类型，-1：没有认证，0，认证用户，2,3,5: 企业认证，220: 达人
    var userVipImage: UIImage? {
        switch (status.user?.verified_type ?? -1) {
        case 0: return UIImage(named: "avatar_vip")
        case 2, 3, 5: return UIImage(named: "avatar_enterprise_vip")
        case 220: return UIImage(named: "avatar_grassroot")
        default: return nil
        }
    }
    
    /// 配图缩略图
    var thumbnailUrls: [NSURL]?
    var retweetedText: String? {
        
        // 1. 判断是否是转发微博，如果不是直接返回 nil
        guard let s = status.retweeted_status else {
            return nil
        }
        
        // 2. s 就是转发微博
        return "@" + (s.user?.screen_name ?? "") + ":" + (s.text ?? "")
    }
    
    /// 构造函数
    init (status: XKStatus) {
        self.status = status
        
        // 创建配图url数组
        let urls = status.retweeted_status?.pic_urls ?? status.pic_urls
        if urls?.count >= 0 {
            thumbnailUrls = [NSURL]()
            
            for dict in status.pic_urls! {
                let url = NSURL(string: dict["thumbnail_pic"]!)
                
                thumbnailUrls?.append(url!)
            }
        }
//        print(thumbnailUrls)
    }
    
    /// 描述信息
    var description: String {
        return status.description + "\n配图数组 \((thumbnailUrls ?? []) as NSArray)"
        
    }
}